import React, { useEffect, useState } from 'react'
import http from '../../api/http'
import type { FormProps } from 'antd';
import { Checkbox, Form, Input } from 'antd';
import { Space, Table, Tag, Drawer } from 'antd';
import type { TableProps } from 'antd';
import type { PopconfirmProps } from 'antd';
import { Button, message, Popconfirm } from 'antd';
import {useNavigate} from 'react-router-dom'
function Index() {
  const [form] = Form.useForm();
  const [forms] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [flag, setFlag] = useState(false);
  const [data, setdata] = useState([])
  const [del, setdel] = useState([])
  const [title, settitle] = useState()
  const [tag, settag] = useState()
  const [edid, setedid] = useState()
  const [total, settotal] = useState()
  const [page, setpage] = useState()
  const [pageSize, setpageSize] = useState()
  const navigate=useNavigate()
  const getdata = () => {
    const params = { page, pageSize }
    if(title) params.keyword=title
    if(tag) params.tag=tag
    http.get('/article/list', {
      params
    }).then((res) => {
      console.log(res);
      if (res.status === 200) {
        setdata(res.data.rows)
        settotal(res.data.count)
      }

    })

  }
  useEffect(() => {
    getdata()
  }, [page, pageSize,title,tag])
  interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
  }

  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      render: (text,record) =>{
        return <div onClick={()=>navigate(`/message?id=${record.id}`)}>{text}</div>
      }
         
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',

    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '操作时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : 'green';

            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">

          <Button onClick={() => Edit(record)}>编辑</Button>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const tiaoShu = (pages, pageSizes) => {
    setpage(pages)
    setpageSize(pageSizes)
  }

  const confirm: PopconfirmProps['onConfirm'] = (e) => {
    console.log(e);
    const shan = data.filter((t) => t.id !== e)
    setdata(shan)
    message.success('Click on Yes');
  };

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e);
    message.error('Click on No');
  };
  const rowactions = (id) => {
    setdel(id)
  }
  const shanAdds = () => {
    const shan = data.filter((item) => !del.includes(item.id))
    setdata(shan)
    message.error('Click on No');
  }
  const add = () => {
    setOpen(true);
    setFlag(true)
    form.resetFields()
  }
  const Edit = (item) => {
    setOpen(true);
    setFlag(false)
    form.setFieldsValue(item)
    setedid(item.id)
  }
  const onClose = () => {
    setOpen(false);
  };


  const onFinish = () => {

    const { title, content } = form.getFieldsValue()
    if (!flag) {
      http.put(`/article/${edid}`, {
        title,
        content,
        tagList: ["HTTP"],
        categoryList: ["HTTP"],

      }).then((res) => {
        console.log(res);
        if (res.status === 204) {
          getdata()
          setOpen(false)
        }

      })

    } else {
      http.post('/article', {
        title,
        content,
        tagList: ["HTTP"],
        categoryList: ["HTTP"],
        authorId: 47529555

      }).then((res) => {
        console.log(res);
        if (res.status === 200) {
          getdata()
          setOpen(false)
          form.resetFields()
        }

      })
    }
  };
  const onFinishOk = (value) => {
    settag(value.tag)
    settitle(value.title)

  }



  return (
    <div>
      <Button onClick={add}>新增</Button>
      <Button onClick={shanAdds}>批量删除</Button>
      <Form
        form={forms}
        name="basic"
        layout="inline"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinishOk}

        autoComplete="off"
      >
        <Form.Item
          label="标题"
          name="title"

        >
          <Input />
        </Form.Item>

        <Form.Item
          label="标签"
          name="tag"

        >
          <Input  />
        </Form.Item>



        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>
      <Table<DataType>
        columns={columns}
        dataSource={data}
        rowKey='id'
        rowSelection={{
          type: 'checkbox',
          onChange: rowactions
        }}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `总 ${total} 条`,
          onChange: tiaoShu
        }
        }
      />
      <Drawer
        title={flag ? '新增' : "编辑"}
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={open}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}

          initialValues={{ remember: true }}
          onFinish={onFinish}

          autoComplete="off"
        >
          <Form.Item
            label="标题"
            name="title"

          >
            <Input />
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"

          >
            <Input />
          </Form.Item>



          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
          <Form.Item label={null}>
            <Button type="primary" >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default Index
